#include "spriteSheet.h"
#include <stdio.h>
SpriteSheet::SpriteSheet(int aWidth, int aHeight, int aNbStep, int aInterval, int aTime, Texture * aTexture) :
Animation(aTime, aInterval, aNbStep), texture(aTexture)
{
	width=(float)aWidth/(float)texture->width;
	height=1.0;
	currentStep=1;

	glGenBuffers(1, &textureIndexBuffer);
	glBindBuffer(GL_ARRAY_BUFFER, textureIndexBuffer);
	
	float texCoord[8]=				/*!<	Coordoonées de la texture		*/
	{
		0.0, 1.0,
		width*currentStep, 1.0,
		width*currentStep, 0.0,
		0.0, 0.0
	};
	
	glBufferData(GL_ARRAY_BUFFER,sizeof(float)*8,texCoord,GL_STREAM_DRAW);
}

void SpriteSheet::CheckTime(int currentTime)
{
	if(currentTime>time+interval)
	{
		NextStep();
		time=currentTime;
	}
}

void SpriteSheet::NextStep()
{
	currentStep++;
	if(currentStep==nbStep+1)
	{
		currentStep=1;
	}
	
	float texCoord[8]=
	{
		width*(currentStep-1), 1.0,
		width*currentStep, 1.0,
		width*currentStep, 0.0,
		width*(currentStep-1), 0.0
	};
	
	glBindBuffer(GL_ARRAY_BUFFER, textureIndexBuffer);
	glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(float)*8,texCoord);
 
}

void SpriteSheet::Use()
{
	glEnable(GL_TEXTURE_2D);
        
	texture->Use();
	glBindBuffer(GL_ARRAY_BUFFER, textureIndexBuffer);
	glTexCoordPointer(2, GL_FLOAT, 0, 0);
}
